from fastapi import FastAPI, Query
import hashlib
import urllib
import urllib.request
import json
from urllib import parse, request
from pydantic import BaseModel
import qrcode
import uvicorn
class Qrcode(BaseModel):
    url_img_txt: str= None
    value: str=None


app = FastAPI()


# @app.get("/")
# async def root(signature: str = '', echostr: str = '', timestamp: str = '', nonce: str = ''):
#     token = "chaodyna"
#     # 获取请求中的参数，计算验证
#     list = [token, timestamp, nonce]
#     list.sort()
#     sha1 = hashlib.sha1()
#     sha1.update(list[0].encode('utf-8'))
#     sha1.update(list[1].encode('utf-8'))
#     sha1.update(list[2].encode('utf-8'))
#     hashcode = sha1.hexdigest()
#     if hashcode == signature:
#         print('succeed')
#         # 需返回数字，而非字符串
#         return int(echostr)
#     else:
#         print('failed')
#         return 0


@app.post("/fastapi/qrone/")
async  def po_qrcode(*,
                     qrc:Qrcode):
   img = qrcode.make(qrc.url_img_txt)
   if(qrc.url_img_txt.find('https://') == 0):
       img_name = "https_" + str(hash(qrc.url_img_txt)) + ".png"
   elif(qrc.url_img_txt.find('http://') == 0):
       img_name = "http_" + str(hash(qrc.url_img_txt)) + ".png"
   else:
       img_name = "qr_"+str(hash(qrc.url_img_txt))+".png"


   img.save(img_name)
   print("answer")
   return {"value":qrc.url_img_txt, "url": "http://127.0.0.1:8100/" + img_name}

@app.get("/qrcode")
async def post_qrcode():
    appid = "wx2bd5781ed5a4c70c"
    secret = "3aaa08e38a5dfa8dcf5ed9b344366976"
    access_token_url = token_url(appid, secret)
    f = urllib.request.urlopen(access_token_url)
    json_string = f.read()
    print(json_string)
    access_token = json.loads(json_string)['access_token']
    ticket_url = get_ticket_url(access_token)
    body = {"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}
    json_data = json.dumps(body).encode(encoding='utf-8')
    req = request.Request(url=ticket_url, data=json_data)
    res = request.urlopen(req).read()
    ticket_string = json.loads(res)['ticket']
    exchange_by_ticker_url = exchange_by_ticket(ticket_string)
    return exchange_by_ticker_url


def token_url(appid, secret):
    return "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (appid, secret)


def get_access_token(appid, secret):
    access_token_url = token_url(appid, secret)
    f = urllib.request(access_token_url)
    json_string = f.read()
    return json.loads(json_string)['access_token']



def get_ticket_url(access_token):
    url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s" %(access_token)
    return url



def exchange_by_ticket(ticket_string):
    ticket = ticket_string
    exchange_by_ticker_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s" % (ticket)
    return exchange_by_ticker_url

if __name__ == "__main__":
    uvicorn.run(app='main:app', host='127.0.0.1', port=8100, reload=True)